<template>
  <div class="warehousing">
    <div class="center">
      <p class="title">填写订单信息</p>
      <!-- 租赁公司信息 -->
      <span class="mainMessage">租赁公司信息</span>
      <div class="box">
        <div>
          <span>公司名称：{{ userInformation.companyName }}</span>
          <span>联系人：{{ userInformation.contactName }}</span>
          <span>联系方式:{{ userInformation.contactPhone }}</span>
        </div>
        <div>
          <span>统一社会信用代码：{{ userInformation.companyCode }}</span>
          <span>法人：{{ userInformation.legalIdName }}</span>
          <span>法人联系方式:{{ userInformation.legalPhone }}</span>
        </div>
      </div>
      <!-- 租赁费用信息 -->
      <div class="mainMessage">租赁费用信息</div>
      <div class="houseMessage" v-for="(item, i) in housemassage" :key="i">
        <span v-show="i === 0">仓储信息</span>
		<div class="line" v-show="i === 0"></div>
        <span
          >房屋区域：<span class="msg">{{ item.projectRegionStage }}期 &nbsp;&nbsp;{{ item.projectRegionId }}区</span></span
        >
        
        <el-table :data="item.projectList" style="width: 100%" border :header-cell-style="{ background: '#EFEFEF' }">
          <el-table-column type="index" label="序号" > </el-table-column>
          <el-table-column prop="projectNumber" label="场地编号" ></el-table-column>
          <el-table-column prop="projectArea" label="面积(㎡)" ></el-table-column>
          <el-table-column prop="projectUnitPrice"  label="租赁单价(元/㎡.月)"></el-table-column>
        </el-table>
      </div>
      <!-- 租金 -->
      <div class="rent rents">
        <div>
          <span>租赁金额明细</span>
          <div class="line"></div>
        </div>
        <div class="check">
          <!-- 租赁开始日期 -->
          <div class="date">
            <span>租赁开始日期:</span>
            <el-date-picker v-model="date" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" :picker-options="pickerOptions" @change="handleChangeDate"> </el-date-picker>
          </div>
          <!-- 租赁月份 -->
          <div class="month">
            <span>租赁月份:</span>
            <el-cascader v-model="value" :options="options" @change="handleChange"> </el-cascader>
          </div>
        </div>
		<div style="background-color: #EFEFEF; padding-left:15px;padding-right: 20px;">
			<span>租金</span>
			<span v-show="isCoupon" class="delay">{{coupon.name}}</span>
			<span style="float: right; padding: 3px 0">小计：
				<span class="color">{{ calculation.rentAmount }}元</span>
			</span>
		</div>
        <table border="1" class="ordermessage">
          <thead>
            <tr>
              <th class="table-color">租赁起止时间</th>
              <td style="width: 25%;">{{ transactionTime }}</td>
              <th class="table-color">租赁总面积</th>
              <td style="width: 15%;">{{ calculation.projectArea }}㎡</td>
              <th class="table-color">税率</th>
              <td>9%</td>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th class="table-color">计费时间</th>
              <td style="width: 25%;">{{ transactionTime }}</td>
              <th class="table-color">收费金额（元）</th>
              <td colspan="3">{{ hoseMoney }}</td>
            </tr>
          </tbody>
        </table>
        <div style="background-color: #f7f7f7; padding-left:15px;padding-right: 20px;">
          <span>市场管理服务费</span>
          <span style="float: right; padding: 3px 0">小计：<span class="color">{{ calculation.marketAmount }}元</span></span
          >
        </div>
        <table border="1" class="ordermessage">
          <thead>
            <tr>
              <th class="table-color">单价</th>
              <td style="width: 25%;">5元/㎡.月</td>
              <th class="table-color">税率</th>
              <td>6%</td>
            </tr>
          </thead>
          <tbody>
            <tr>
              <th class="table-color">计费时间</th>
              <td style="width: 25%;">{{ transactionTime }}</td>
              <th class="table-color">收费金额（元）</th>
              <td>{{ serviceCharge }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="else">
        <span class="else-span" style="padding-right: 20px;">
          <span>其他服务：</span>
			<span class="elsething" v-for="(item, i) in market_service" :key="i">
				<a :href="item['remarks']" style="text-decoration:none; color: #666666;">{{item['value']}}</a>
			</span>
        </span>
      </div>
		<div class="pay" style="color: #606266; padding-right: 20px;" v-show="isCoupon">
			<span>优惠活动：{{coupon.name}}</span>
		</div>
      <div class="pay" style="padding-right: 20px;margin-top: 15px;">
		<el-radio-group v-model="radio1" v-show="radio == 2">
			<el-radio-button label="上海">1000.00元X2期</el-radio-button>
			<el-radio-button label="北京">10001.00元X12期</el-radio-button>
			<el-radio-button label="广州">10002.00元X12期</el-radio-button>
			<el-radio-button label="深圳">100022.00元X12期</el-radio-button>
		</el-radio-group>
		<el-radio v-model="radio" label="2">分期付款</el-radio>
        <el-radio v-model="radio" label="1">全款支付</el-radio>
        <span style="color: #606266; padding-top: 7px;">支付方式：</span>
      </div>
      <div class="total" style="padding-right: 20px;">
        <span class="total-text">应付金额（元）：{{ calculation.totalAmount }}元</span>
      </div>
      <div class="submit">
        <el-button type="primary" class="submit-btn" @click="confirm">确认提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getItem } from '@/utils/store.js'
import { getHoserent, getStorageList, getCompute, append } from '@/views/BasicServicesPark/api/orderInformation.js'
export default {
  data() {
    return {
		pickerOptions: {
			disabledDate(time) {
				if(time.getTime() < Date.now() - (3600 * 1000 * 24) || time.getTime()  > Date.now() + (3600 * 1000 * 24 * 7)){
					return  true;
				}else{
					return  false;
				}
			},
		},
		isCoupon: false,
		radio1:'',
		chooseRentTime: 12,
		coupon:{
			name:'',
			discountTime: 0,
			discountAmount:0,
		},
		market_service: [],
      date: '',
      value: [12],
      radio: '1',
      transactionTime: '2019.09.17-2020.10.16', //起止时间
      condition: {
        ids: ''
      }, //查看房屋的id集合
      StorageLists: {
        ids: ''
      },
      calculation: {},
      userInformation: {}, //商户的信息
      housemassage: [], //查看房屋的信息
      hoseMoney: 0, //收费金额
      serviceCharge: 0,
      rentEndTime: '',
      tableData1: [
        {
          index: '1',
          number: 'A1-1',
          area: '123',
          price: '13'
        },
        {
          index: '2',
          number: 'A1-2',
          area: '100',
          price: '13'
        }
      ],
      tableData2: [
        {
          index: '1',
          number: 'B1-1',
          area: '123',
          price: '13'
        },
        {
          index: '2',
          number: 'B1-2',
          area: '100',
          price: '13'
        }
      ],
      options: [
        {
          value: 12,
          label: '12个月'
        },
        {
          value: 11,
          label: '11个月'
        },
        {
          value: 10,
          label: '10个月'
        },
        {
          value: 9,
          label: '9个月'
        },
        {
          value: 8,
          label: '8个月'
        },
        {
          value: 7,
          label: '7个月'
        },
        {
          value: 6,
          label: '6个月'
        },
        {
          value: 3,
          label: '3个月'
        }
      ]
    }
  },
  created() {
    this.getuserMessage()
    this.getStorageLists()
    this.getComputes()
	this.getCoupon()
	this.getMarkService()
	this.initData()
  },
  methods: {
	initData() {
		const dt = new Date()
		const y = dt.getFullYear()
		const m = (dt.getMonth() + 1 + '').padStart(2, '0')
		const d = (dt.getDate() + '').padStart(2, '0')
		this.date = `${y}-${m}-${d}`
		this.handleChange(this.chooseRentTime)
	},
	async getMarkService(){
		const { data: res } = await this.$http.get(`/admin/dict/type/market_service`)
		let that = this
		res.data.forEach(item => {
			that.market_service.push({'value': item['description'], 'remarks':item['remarks'] })
		})
	},
	async getCoupon() {
		let that = this
		let id = getItem('XIE_XIN').user_id
		let companyId = getItem('USER_INFO').data.data.companyId
		let params = {
			id:companyId
		}
		const { data: res } = await that.$http.get(`/config/sysCouponInfo/company/${id}`, {
			params: params
		})
		if(res.code == 0 && res.data){
			that.isCoupon = true
			that.getCouponType(res.data[0])
		}
  },
  async getCouponType(data){
		let that = this 
		const { data: res } = await this.$http.get(`/admin/dict/type/coupon_type`)
		res.data.forEach( item => {
			if(item['label'] == data['type']){
				that.coupon.name = item['value']
				that.coupon.discountTime = data['timeLimit']
			}
		})
  },
    async getuserMessage() {
      let id = getItem('XIE_XIN').user_id
      // console.log(id)
      const { data: res } = await getHoserent(id)
      this.userInformation = res.data
      // console.log(res)
      // console.log(that.total)
      if (res.code !== 0) {
        return this.$message.error('获取商户信息失败！')
      }
      // that.tableData = res.data.records
      // console.log(that.tableData)
    },
    async getStorageLists() {
      let that = this
      that.StorageLists.ids = getItem('storageChooesLists').toString()
      // console.log(that.$route.query.id)
      const { data: res } = await getStorageList(that.StorageLists)
      that.housemassage = res.data

		if(that.housemassage){
			that.hoseMoney = 0
			that.housemassage.forEach(e => {
				e.projectList.forEach(item =>{
					that.hoseMoney += item.projectUnitPrice * item.projectArea
				})
				
			})
			that.hoseMoney = ((that.hoseMoney * (that.chooseRentTime + 1)) / (1 + 0.9)).toFixed(2)
		}
      if (res.code !== 0) {
        return that.$message.error('获取房屋信息失败！')
      }
    },

    async getComputes() {
      let ids = getItem('storageChooesLists')
		//let that = this
      let dat = {
        //discountTime: 1,
        rentTime: this.value[0],
        ids: ids,
        orderType: 1
      }
      const { data: res } = await getCompute(dat)
		if(res.code === 0){
			this.calculation = res.data
		}
		let that = this
		if(that.housemassage){
			that.hoseMoney = 0
			that.housemassage.forEach(e => {
				e.projectList.forEach(item =>{
					that.hoseMoney += item.projectUnitPrice * item.projectArea
				})
				
			})
			that.hoseMoney = ((that.hoseMoney * (that.chooseRentTime + 1)) / (1 + 0.9)).toFixed(2)
		}
		that.serviceCharge = ((that.calculation.projectArea * that.chooseRentTime) / (1 + 0.6)).toFixed(2)
		
      
      // this.handleChange(this.value[0])
    },
	handleChangeDate(dd){
		this.date = dd
		this.changeTime(this.chooseRentTime)
	},
    handleChange(mm) {
      let that = this
      that.getComputes()
		that.changeTime(mm)
    },
	changeTime(mm){
		let that = this
		that.chooseRentTime =parseInt(mm) 
		const dt = new Date(that.date)
		const y = dt.getFullYear()
		const m = (dt.getMonth() + 1 + '').padStart(2, '0')
		const d = (dt.getDate() + '').padStart(2, '0')
		var newM = parseInt(m) + parseInt(mm) + 1
		// console.log(newM)
		if (newM > 12) {
			var endY = y + 1
			var endM = newM - 12
			that.transactionTime = `${y}-${m}-${d}--${endY}-${endM}-${d}`
			that.rentEndTime = `${endY}-${endM}-${d}`
		}
		if (newM == 12) {
			const equalY = y + 1
			const equalM = newM
			that.transactionTime = `${y}-${m}-${d}--${equalY}-${equalM}-${d}`
			that.rentEndTime = `${endY}-${endM}-${d}`
		}
		if (newM < 12) {
			const LessThanY = y
			const LessThanM = newM
			that.transactionTime = `${y}-${m}-${d}--${LessThanY}-${LessThanM}-${d}`
			that.rentEndTime = `${endY}-${endM}-${d}`
		}
	},
    async confirm() {
      let userId = getItem('XIE_XIN').user_id
      let parentId = getItem('USER_INFO').data.data.parentId
      let companyId = getItem('USER_INFO').data.data.companyId
      // let companyName = getItem('USER_INFO').data.data.companyName
      let date = {
        // orderNumber: '',
        userId: userId,
        parentId: parentId,
        companyId: companyId,
        // companyName: '重庆龙廷汽车销售有限公司',
        serviceType: 2, //服务类型1.房屋租赁
        orderType: 1, //订单类型1.租赁合同2.缴费合同
        // orderAmount: '',//订单金额
        // couponNumber: '',
        rentStartTime: this.date,
        rentEndTime: this.rentEndTime,
        feeEndTime: this.rentEndTime,
        discountTime: this.coupon.discountTime,
        rentTime: this.value[0],
        rentAmount: this.calculation.rentAmount,
        // rentTaxAmount: '',
        guaranteeAmount: this.calculation.guaranteeAmount,
        marketFee: this.calculation.marketAmount,
        // marketTaxAmount: '',
        //discountAmount: this.coupon.discountAmount,
        totalAmount: this.calculation.totalAmount,
        projectIds: this.StorageLists.ids.split(',')
      }
      // console.log(date)
      const { data: res } = await append(date)
      if (!res.code == 0) {
        this.$message({
          type: 'warning',
          offset: 200,
          message: res.msg
        })
        return
      }
      // this.$router.push({ name: 'payment', param: { id: res.data.orderNumber, } })
      this.$router.push({ path: '/payment', query: { id: res.data.orderNumber, money: this.calculation.totalAmount } })
    }
    // confirm() {
    //   this.$router.push({ name: 'payment', param: { id: '2' } })
    // }
  }
}
</script>

<style lang="less">
@import './warehousing.less';
.pay .el-radio{
	font-size: 30px;
}
</style>
